<template>
  <div class="activity-manage">
    <!-- 操作栏 -->
    <div class="actions">
      <el-button type="primary" @click="openDialog">新增活动</el-button>
    </div>

    <!-- 活动表格 -->
    <div class="table-wrapper">
      <el-table :data="activityList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="活动名称" min-width="160" />
        <el-table-column prop="type" label="活动类型" width="120" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              style="width: 80px; height: 50px"
              fit="cover"
              @click="openPreview(row.image)"
            />
            <span v-else class="text-gray">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="110" />
        <el-table-column label="奖项(等级 · 名称 · 概率%)">
          <template #default="{ row }">
            <div v-for="p in prizesByActivity(row.id)" :key="p.id" class="prize-row">
              <el-tag size="small">{{ p.level }}</el-tag>
              <span style="margin-left: 6px">{{ p.name }}</span>
              <span class="text-gray" style="margin-left: 6px">（{{ p.probability }}%）</span>
            </div>
            <div v-if="prizesByActivity(row.id).length === 0" class="text-gray">无奖项</div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="detailActivity(row)">详情</el-button>
            <el-button size="small" type="primary" @click="editActivity(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeActivity(row.id)">删除</el-button>
            <el-button size="small" @click="goPrizeManage(row)">奖品管理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑活动' : '新增活动'"
      width="950px"
      @close="resetForm"
    >
      <el-form :model="form" label-width="120px">
        <el-row :gutter="16">
          <!-- 基本信息 -->
          <el-col :span="12">
            <el-form-item label="活动名称" required>
              <el-input v-model="form.name" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="活动类型" required>
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option label="大转盘" value="lottery" />
                <el-option label="签到" value="sign" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开始时间" required>
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="结束时间" required>
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="活动图片">
              <el-upload
                class="upload-demo"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleActivityImageChange"
              >
                <div v-if="form.image">
                  <img :src="form.image" style="width: 100%; height: 100%; object-fit: cover" />
                </div>
                <div v-else class="upload-placeholder">
                  <el-icon><Plus /></el-icon>
                  <div style="font-size: 12px">上传图片</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>

          <!-- 奖品配置卡片布局 -->
          <el-col :span="24">
            <el-form-item label="奖项配置">
              <div class="prize-tools">
                <el-button size="small" @click="addPrizeRow">新增奖项</el-button>
                <div class="text-gray">
                  已用概率：{{ usedProbability }}% ，剩余：{{ 100 - usedProbability }}%
                </div>
              </div>

              <div class="prize-card-container">
                <div
                  v-for="(p, idx) in form.prizes"
                  :key="p.__tempId ?? p.id ?? idx"
                  class="prize-card"
                  draggable="true"
                  @dragstart="onDragStart($event, idx)"
                  @dragover.prevent
                  @drop="onDrop($event, idx)"
                >
                  <div class="prize-image">
                    <img v-if="p.image" :src="p.image" alt="thumb" @click="openPreview(p.image)" />
                    <div v-else class="upload-placeholder-small">
                      <el-icon><Plus /></el-icon>
                      <div style="font-size: 12px">上传</div>
                      <input
                        type="file"
                        accept="image/*"
                        @change="e => handlePrizeFileChange(e, idx)"
                      />
                    </div>
                  </div>

                  <div class="prize-info">
                    <el-input v-model="p.level" placeholder="等级" size="small" />
                    <el-input v-model="p.name" placeholder="奖品名称" size="small" />
                    <el-input-number v-model="p.quantity" :min="0" size="small" />
                    <el-input-number v-model="p.probability" :min="0" :max="100" size="small" />
                  </div>

                  <div class="prize-ops">
                    <el-button size="mini" type="danger" @click="removePrizeRow(idx)"
                      >删除</el-button
                    >
                    <el-button size="mini" @click="moveUp(idx)" :disabled="idx === 0"
                      >上移</el-button
                    >
                    <el-button
                      size="mini"
                      @click="moveDown(idx)"
                      :disabled="idx === form.prizes.length - 1"
                      >下移</el-button
                    >
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveActivity">保存</el-button>
      </template>
    </el-dialog>

    <!-- 活动详情弹窗 -->
    <el-dialog v-model="detailVisible" title="活动详情" width="700px">
      <div v-if="detail">
        <div style="display: flex; gap: 16px">
          <div style="flex: 0 0 160px">
            <el-image
              v-if="detail.image"
              :src="detail.image"
              style="width: 160px; height: 100px"
              fit="cover"
            />
            <div v-else class="text-gray">无图片</div>
          </div>
          <div style="flex: 1">
            <p><strong>名称：</strong>{{ detail.name }}</p>
            <p><strong>类型：</strong>{{ detail.type }}</p>
            <p><strong>时间：</strong>{{ detail.startTime }} 至 {{ detail.endTime }}</p>
            <p><strong>状态：</strong>{{ detail.status }}</p>
          </div>
        </div>

        <el-divider>奖项</el-divider>
        <el-table :data="prizeListForDetail" border style="width: 100%">
          <el-table-column prop="level" label="等级" width="120" />
          <el-table-column prop="name" label="奖品名称" />
          <el-table-column label="图片" width="120">
            <template #default="{ row }">
              <el-image
                v-if="row.image"
                :src="row.image"
                style="width: 80px; height: 50px"
                fit="cover"
              />
              <span v-else class="text-gray">无</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="probability" label="概率(%)" width="120" />
        </el-table>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewVisible" width="600px">
      <img :src="previewImageUrl" style="width: 100%; height: auto" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import {
  getActivityList,
  addActivity,
  updateActivity,
  deleteActivity,
  type Activity
} from '@/api/activity'
import {
  getPrizeList,
  getPrizesByActivity,
  addPrize,
  updatePrize,
  deletePrize,
  type Prize
} from '@/api/prize'

const router = useRouter()
const activityList = ref<Activity[]>([])
const prizeAll = ref<Prize[]>([])

const dialogVisible = ref(false)
const detailVisible = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')

const detail = ref<Activity | null>(null)
const prizeListForDetail = ref<Prize[]>([])

type PrizeForm = Partial<Prize> & { __tempId?: number }
type ActivityForm = Activity & { prizes: PrizeForm[] }

const form = ref<ActivityForm>({
  id: 0,
  name: '',
  type: 'lottery',
  status: '未开始',
  startTime: '',
  endTime: '',
  image: '',
  prizes: []
})

const removedPrizeIds = ref<number[]>([])

async function loadData(): Promise<void> {
  activityList.value = await getActivityList()
  prizeAll.value = await getPrizeList()
}
onMounted(loadData)

function prizesByActivity(activityId: number): Prize[] {
  return prizeAll.value.filter(p => p.activityId === activityId)
}

function handleActivityImageChange(file: UploadFile): void {
  const raw = file.raw as File | undefined
  if (!raw) return
  const reader = new FileReader()
  reader.onload = e => {
    form.value.image = e.target?.result as string
  }
  reader.readAsDataURL(raw)
}

function openDialog(): void {
  form.value = {
    id: 0,
    name: '',
    type: 'lottery',
    status: '未开始',
    startTime: '',
    endTime: '',
    image: '',
    prizes: []
  }
  removedPrizeIds.value = []
  dialogVisible.value = true
}

async function editActivity(row: Activity): Promise<void> {
  form.value = {
    ...row,
    prizes: (await getPrizesByActivity(row.id)).map(p => ({ ...p }))
  }
  form.value.prizes.forEach((p, i) => {
    if (!p.__tempId) p.__tempId = Date.now() + i
  })
  removedPrizeIds.value = []
  dialogVisible.value = true
}

async function removeActivity(id: number): Promise<void> {
  try {
    await ElMessageBox.confirm('确认删除该活动及其所有奖品？', '删除确认', { type: 'warning' })
    await deleteActivity(id)
    const toDelete = prizeAll.value.filter(p => p.activityId === id).map(p => p.id)
    for (const pid of toDelete) await deletePrize(pid)
    ElMessage.success('删除成功')
    await loadData()
  } catch (err) {
    console.error(err)
  }
}

async function detailActivity(row: Activity): Promise<void> {
  detail.value = row
  prizeListForDetail.value = await getPrizesByActivity(row.id)
  detailVisible.value = true
}

function goPrizeManage(row: Activity): void {
  router.push({ name: 'prizeManage', query: { activityId: String(row.id) } })
}

function openPreview(url: string | undefined): void {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

function addPrizeRow(): void {
  form.value.prizes.push({
    __tempId: Date.now() + Math.floor(Math.random() * 1000),
    level: '',
    name: '',
    quantity: 1,
    probability: 0,
    image: ''
  })
}

function removePrizeRow(index: number): void {
  const p = form.value.prizes[index]
  if (p && (p as Prize).id) removedPrizeIds.value.push((p as Prize).id)
  form.value.prizes.splice(index, 1)
}

function handlePrizeFileChange(e: Event, idx: number): void {
  const input = e.target as HTMLInputElement
  const files = input.files
  if (!files || files.length === 0) return
  const reader = new FileReader()
  reader.onload = ev => {
    form.value.prizes[idx].image = ev.target?.result as string
  }
  reader.readAsDataURL(files[0])
}

let dragSrcIndex = -1
function onDragStart(e: DragEvent, index: number): void {
  dragSrcIndex = index
  e.dataTransfer?.setData('text/plain', String(index))
  if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move'
}

function onDrop(e: DragEvent, toIndex: number): void {
  e.preventDefault()
  const src = Number(e.dataTransfer?.getData('text/plain') ?? dragSrcIndex)
  if (Number.isNaN(src)) return
  if (src === toIndex) return
  const arr = form.value.prizes
  const [moved] = arr.splice(src, 1)
  arr.splice(toIndex, 0, moved)
}

function moveUp(index: number): void {
  if (index <= 0) return
  const arr = form.value.prizes
  const t = arr[index - 1]
  arr[index - 1] = arr[index]
  arr[index] = t
}

function moveDown(index: number): void {
  if (index >= form.value.prizes.length - 1) return
  const arr = form.value.prizes
  const t = arr[index + 1]
  arr[index + 1] = arr[index]
  arr[index] = t
}

const usedProbability = computed(() =>
  form.value.prizes.reduce((s, p) => s + (Number(p.probability) || 0), 0)
)

async function saveActivity(): Promise<void> {
  if (!form.value.name) {
    ElMessage.error('请输入活动名称')
    return
  }
  if (!form.value.startTime || !form.value.endTime) {
    ElMessage.error('请选择活动时间')
    return
  }
  if (usedProbability.value > 100) {
    ElMessage.error('奖项总概率不能超过 100%')
    return
  }

  try {
    if (form.value.id) {
      await updateActivity({ ...form.value })
    } else {
      const newAct = await addActivity({ ...form.value })
      form.value.id = newAct.id
    }

    for (const pid of removedPrizeIds.value) await deletePrize(pid)
    removedPrizeIds.value = []

    for (const p of form.value.prizes) {
      const payload = {
        activityId: form.value.id!,
        level: p.level || '奖项',
        name: p.name || '奖品',
        quantity: Number(p.quantity) || 0,
        probability: Number(p.probability) || 0,
        image: p.image || ''
      }
      if ((p as Prize).id) await updatePrize({ ...(p as Prize) })
      else await addPrize(payload)
    }

    ElMessage.success('保存成功')
    dialogVisible.value = false
    await loadData()
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

function resetForm(): void {
  form.value = {
    id: 0,
    name: '',
    type: 'lottery',
    status: '未开始',
    startTime: '',
    endTime: '',
    image: '',
    prizes: []
  }
  removedPrizeIds.value = []
}
</script>

<style scoped>
.table-wrapper {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  overflow-x: auto; /* 保持表格横向滚动可用 */
}
.activity-manage {
  padding: 16px;
}
.actions {
  margin-bottom: 16px;
}
.text-gray {
  color: #888;
}

.prize-tools {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}
.prize-card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.prize-card {
  width: 200px;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 8px;
  display: flex;
  flex-direction: column;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.prize-image {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 6px;
  position: relative;
}
.prize-image img {
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
  object-fit: cover;
}
.upload-placeholder-small {
  width: 100%;
  height: 100%;
  border: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 12px;
  position: relative;
}
.upload-placeholder-small input {
  position: absolute;
  opacity: 0;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  cursor: pointer;
}

.prize-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 6px;
}
.prize-info input,
.prize-info .el-input-number {
  width: 100%;
}

.prize-ops {
  display: flex;
  gap: 4px;
  justify-content: space-between;
}
</style>
